package com.ebrothers.isns.data;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.ebrothers.isns.common.Constants;
import com.ebrothers.isns.vo.Question;

public class QsRetrieveSchedule {
	private static final String TAG = "QsRetrieveSchedule";
	public static final int STATE_IDLE = -1;
	public static final int STATE_RUNNING = 0;
	public static final int STATE_PAUSED = 1;
	public static final int STATE_DESTORYED = 2;
	private static final int POST_RESULT = 1;
	private String mLastDate = null;
	private Timer mTimer;
	private int mState = STATE_IDLE;
	private TimerTask mTimerTask;

	final Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case POST_RESULT:
				if (Constants.LOGD) {
					Log.d(TAG, "****** handleMessage. POST_RESULT");
				}
				if (mListener != null) {
					mListener.onQsRetrieved((ArrayList<Question>) msg.obj);
				}
				break;
			}
			super.handleMessage(msg);
		}
	};
	private OnQsRetrievedListener mListener;

	public void setOnQsRetrievedListener(OnQsRetrievedListener listener) {
		mListener = listener;
	}

	public void execute() {
		if (Constants.LOGD) {
			Log.d(TAG, "****** execute. ");
		}
		mTimer = new Timer();
		mTimerTask = createTimerTask();
		mTimer.schedule(mTimerTask, 0, 10000);
		mState = STATE_RUNNING;
	}

	private TimerTask createTimerTask() {
		return new TimerTask() {
			public void run() {
				ArrayList<Question> qs = null;
				if (mLastDate == null) {
					qs = QsInteractor.getQuestions("*");
				} else {
					qs = QsInteractor.getQuestions(mLastDate);
				}

				if (!qs.isEmpty()) {
					mLastDate = qs.get(0).datetime;
				}
				final Message message = handler.obtainMessage(POST_RESULT);
				message.obj = qs;
				message.sendToTarget();
			}
		};
	}

	public void resume() {
		if (Constants.LOGD) {
			Log.d(TAG, "****** resume. ");
		}
		execute();
	}

	public void puase() {
		if (Constants.LOGD) {
			Log.d(TAG, "****** puase. ");
		}
		mTimer.cancel();
		mTimer.purge();
		mState = STATE_PAUSED;
	}

	public void destory() {
		if (Constants.LOGD) {
			Log.d(TAG, "****** destory. ");
		}
		mTimer.cancel();
		mTimer.purge();
		mLastDate = null;
		mState = STATE_DESTORYED;
	}

	public void retrieveImmediately() {
		new Thread(mTimerTask).start();
	}

	public boolean isRunning() {
		return mState == STATE_RUNNING;
	}

	public boolean isDestoryed() {
		return mState == STATE_DESTORYED;
	}

	public boolean isPaused() {
		return mState == STATE_PAUSED;
	}

	public interface OnQsRetrievedListener {
		public void onQsRetrieved(ArrayList<Question> newQs);
	}
}
